package com.shulidata.mock.utils;

import com.alibaba.fastjson.JSON;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.TypeMismatchException;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by Fyduan on 2016/4/29.
 */
public class ExceptionHandler extends AbstractHandlerExceptionResolver {

    private static final Logger logger = LogManager.getLogger(ExceptionHandler.class.getName());

    @Override
    protected ModelAndView doResolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {

        logger.error("请求接口 ==> {}\n请求参数 ==> {}",
                httpServletRequest.getRequestURI(),
                JSON.toJSONString(Servlets.getRequestParams(httpServletRequest)),
                e);

        ModelAndView mv = new ModelAndView();
        // 异常类型判断，返回不同的错误代码
        // 1.业务自定义的异常
        if(e instanceof GenericException) {
            mv.addObject(new Result(((GenericException)e).getCode(), e.getMessage()));
        }
        // 2.Spring MVC 参数绑定失败异常
        else if (e instanceof BindException) {
            mv.addObject(new Result(SysCode.ERR_PARAM));
        }
        // 3.Spring MVC 参数不匹配异常
        else if (e instanceof TypeMismatchException) {
            mv.addObject(new Result(SysCode.ERR_PARAM, "参数不匹配"));
        }
        // 4.Spring MVC 参数不存在或类型错误
        else if (e instanceof MissingServletRequestParameterException) {
            mv.addObject(new Result(SysCode.ERR_PARAM, "参数不存在或类型错误"));
        }
        // n.未知异常
        else {
            mv.addObject(new Result(SysCode.ERR_SERVER));
        }

        return mv;
    }
}
